﻿using System;
using Microsoft.Xrm.Sdk;

namespace ScriptEase
{
    static class OrganizationServiceExtension
    {
        private delegate OrganizationResponse RequestHandler(OrganizationRequest request);



        internal delegate void RequestCompletedHandler(OrganizationResponse response, object addData, Exception result);



        public static void BeginRequest(this IOrganizationService orgService, OrganizationRequest request, RequestCompletedHandler requestCompleted, object addData)
        {
            RequestHandler mi = new RequestHandler(orgService.Execute);

            mi.BeginInvoke(request,
                           ar =>
                               {
                                   try
                                   {
                                       OrganizationResponse response = mi.EndInvoke(ar);
                                       requestCompleted(response, ar.AsyncState, null);
                                   }
                                   catch (Exception e)
                                   {
                                       Trace.Default.LogException(e);
                                       requestCompleted(null, ar.AsyncState, e);
                                   }
                               }, addData);
        }
    }
}